package com.cn.wangxin.service.weather.impl;

import com.cn.wangxin.service.weather.WeatherService;
import com.cn.wangxin.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能描述 天气
 *
 * @Created Time 2016/9/23
 * @Edited Time 2016/9/23
 * @Created by wangxin43
 */
public class WeatherServiceImpl implements WeatherService{
    private Logger logger = LoggerFactory.getLogger(WeatherServiceImpl.class);

    private String httpUrl;
    private String apikey;
    private String httpArg;

    /**
     * 获取天气
     * http://www.heweather.com/
     * @param city
     * @return
     */
    public String getWeather(String city) {
        logger.info("城市是:{}",city);
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        String requestUrl = httpUrl + "?" +httpArg+city;
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            // 填入apikey到HTTP header
            connection.setRequestProperty("apikey",apikey);
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
            Map<String,Object> m = JsonUtil.parseMap(result);
            Map<String,Object> ss = new HashMap<String,Object>();
            ss.put("data",m.get("HeWeather data service 3.0"));
            result = JsonUtil.getObj2Json(ss);
            logger.info("result is {}",result);
        } catch (Exception e) {
            logger.error("WeatherServiceImpl getWeather  error,",e);
            e.printStackTrace();
        }
        return result;
    }

    public void setHttpUrl(String httpUrl) {
        this.httpUrl = httpUrl;
    }

    public void setApikey(String apikey) {
        this.apikey = apikey;
    }

    public void setHttpArg(String httpArg) {
        this.httpArg = httpArg;
    }
}
